﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using System.Data;
using BLL;
using System.Net;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

public partial class Spa_weixinreg2 : WeiPage
{
    PersonInfoBO pbo = new PersonInfoBO();
    CUST_MEMBERBO cbo = new CUST_MEMBERBO();
    IntegralChangeBO ibo = new IntegralChangeBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "";
        if (!IsPostBack)
        {
            if (Request.QueryString["code"] != null)
            {
                try
                {
                    string url = string.Format(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GetAppid() + "&secret=" + GetSecret() + "&code={0}&grant_type=authorization_code", Request.QueryString["code"].ToString());
                    string token = PostRequest(url);
                    if (token.Contains("7200"))
                    {
                        string[] b = token.Split('\"');
                        Session["FromUserName"] = b[13];
                        Session["ToUserName"] = GetAppid();
                    }
                }
                catch (Exception)
                {

                }
            }
            if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
            {
                string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                Session["FromUserName"] = user;
                Session["ToUserName"] = user2;
                PersonInfo per = pbo.GetModel(user);
                if (per != null)
                {
                    Label1.Text = "你已注册";
                    Button1.Visible = false;
                    Button2.Visible = false;
                    Response.Redirect("Index.aspx");
                }
            }
            for (int i = 1950; i < DateTime.Now.Year; i++)
            {
                ddlYear.Items.Add(new ListItem(i.ToString() + "年", i.ToString()));
            }
            DataSet city = pbo.GetCityCode();

            foreach (DataRow dr in city.Tables[0].Rows)
            {
                qy.Items.Add(new ListItem(dr["name"].ToString(), dr["code"].ToString()));
            }
        }
    }
    #region
    protected void Button2_Click(object sender, EventArgs e)
    {
        // numT.Value = "60";
        try
        {
            Label1.Text = "";
            if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
            {
                string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                PersonInfo per = pbo.GetModel(user);
                if (per != null)
                {
                    Label1.Text = "你已注册";
                    Button1.Visible = false;
                    Button2.Visible = false;
                }
                else
                {
                    si_DispMember_obService s1 = new si_DispMember_obService();
                    dt_DispMember_req w1 = new dt_DispMember_req();
                    w1.ZTYPE = "0101";
                    w1.MOB_NUMBER = txtPhone.Value.Trim();
                    dt_DispMember_res dt1 = s1.si_DispMember_ob(w1);
                    if (dt1.ZCRMT316 != null)
                    {
                        Label1.Text = "客户已存在，请进行绑定";
                    }
                    else
                    {
                        //PersonInfo per = pbo.GetModel("", txtPhone.Value);
                        //if (per != null)
                        //{
                        if (txtPhone.Value.Length == 11)
                        {
                            Random r = new Random();
                            //int num = 111234;
                            int num = r.Next(100000, 999999);
                            //string message = string.Format("本次微信平台获取的验证码是：" + num);
                            string message = string.Format("本次微信平台获取的验证码是：[[ " + num + "]]。如非本人操作，请致电400-820-3988");
                            string msg = new SendDX().Send(message, txtPhone.Value, 0);
                            if (msg == "发送成功")
                            {
                                Label1.Text = "发送成功,请耐心等待";
                                Session["RanNum"] = num.ToString();
                                // Button2.Visible = false;
                                numT.Value = "60";
                                //AlertMessage("因相关管控，经特殊处理，电信、联通客户将由136-1175-7392发送注册或绑定验证码，该号码仅提供验证码发送服务，请勿直接回复任何信息。");
                                //AlertMessage("请注意查收短信");
                            }
                            else
                            {
                                Label1.Text = "发送失败";
                                Session["RanNum"] = num.ToString();
                            }

                        }
                        else
                        {
                            Label1.Text = "请输入正确的手机号";
                        }
                      
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message.ToString();
        }
    }
    #endregion

    #region
    //protected void Button1_Click(object sender, EventArgs e)
    //{

    //    Label1.Text = "";
    //    if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
    //    {
    //        string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
    //        string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
    //        Session["FromUserName"] = user;
    //        Session["ToUserName"] = user2;
    //        if (txtPhone.Value == "")
    //        {
    //            Label1.Text = "请输入手机号码";
    //        }
    //        else
    //        {
    //            si_DispMember_obService s1 = new si_DispMember_obService();
    //            dt_DispMember_req w1 = new dt_DispMember_req();
    //            w1.ZTYPE = "0101";
    //            w1.MOB_NUMBER = txtPhone.Value.Trim();
    //            dt_DispMember_res dt1 = s1.si_DispMember_ob(w1);
    //            if (dt1.ZCRMT316 != null)
    //            {
    //                Label1.Text = "客户已存在，请进行绑定";
    //            }
    //            else
    //            {
    //                if (xm.Value == "")
    //                {
    //                    Label1.Text = "请输入真实姓名";
    //                }
    //                //else if (sr.Value == "")
    //                //{
    //                //    Label1.Text = "请输入日期";
    //                //}
    //                else if (qy.SelectedValue == "0")
    //                {
    //                    Label1.Text = "请选择区域";
    //                }
    //                else if (ddlYear.SelectedValue == "0")
    //                {
    //                    Label1.Text = "请选择出生年份";
    //                }
    //                //else if (ddlYue.SelectedValue == "0")
    //                //{
    //                //    Label1.Text = "请选择出生月份";
    //                //}
    //                //else if (ddlDay.SelectedValue == "0")
    //                //{
    //                //    Label1.Text = "请选择出生日期";
    //                //}
    //                else if (txtPhone.Value == "")
    //                {
    //                    Label1.Text = "请输入手机号码";
    //                }
    //                else if (dx.Value == "")
    //                {
    //                    Label1.Text = "请输入验证码";
    //                }
    //                else if (Session["RanNum"] != null && Session["RanNum"].ToString() != dx.Value)
    //                {
    //                    Label1.Text = "验证码错误";
    //                }
    //                else
    //                {
    //                    DateTime st = DateTime.Now;
    //                    try
    //                    {

    //                        st = DateTime.Parse(ddlYear.SelectedValue + "-" + ddlYue.SelectedValue + "-" + ddlDay.SelectedValue);
    //                    }
    //                    catch (Exception)
    //                    {
    //                        Label1.Text = "生日格式错误";
    //                        return;
    //                    }
    //                    PersonInfo p = new PersonInfo();
    //                    p.area = qy.SelectedValue;
    //                    p.addr = "";
    //                    p.BIRTHDAY = st;
    //                    p.CreateDate = DateTime.Now;
    //                    p.EMAIL = "";
    //                    p.FromUserName = user;
    //                    p.LAST_DATE = DateTime.Now;
    //                    p.MEM_DATE = DateTime.Now;
    //                    p.MEM_LEVEL = "注册会员";
    //                    p.Name = xm.Value;
    //                    p.PersonNo = "";
    //                    p.Phone = txtPhone.Value;
    //                    p.REMARK = "";
    //                    if (ddlSex.SelectedValue == "0")
    //                    {
    //                        p.Sex = false;
    //                    }
    //                    else
    //                    {
    //                        p.Sex = true;
    //                    }
    //                    p.Store = "";
    //                    p.SumIntegral = 0;
    //                    p.SurplusIntegral = 0;
    //                    p.WX_DATE = DateTime.Now;
    //                    p.YZM = dx.Value;
    //                    int id = pbo.Add(p);
    //                    int no = 820000000;
    //                    no += id;
    //                    if (id > 0)
    //                    {
    //                        Label1.Text = "注册成功";
    //                        try
    //                        {
    //                            p.ID = id;
    //                            p.PersonNo = no.ToString();
    //                            pbo.Update(p);
    //                            ZCRMT316 _ZCRMT316 = new ZCRMT316()
    //                            {
    //                                TYPE = "0101",
    //                                NAME1_TEXT = xm.Value,
    //                                BPEXT = p.PersonNo,
    //                                NAME_FIRST = "",
    //                                NAME_LAST = "",
    //                                BIRTHDT = st,
    //                                BIRTHDTSpecified = true,
    //                                LOGINPASS2 = "666666",
    //                                VKORG = "C016",
    //                                DIVISION = "00",
    //                                ZC014 = "sd",
    //                                ZC015 = "ss",
    //                                ZC016 = "01",
    //                                ZC017 = "01",
    //                                ZC018 = "01",
    //                                ZC019 = "01",
    //                                ZC020 = "s",
    //                                NAMCOUNTRY = "CN",
    //                                MOB_NUMBER = txtPhone.Value,
    //                                REGION = p.area,
    //                                ZC023 = user   //微信号
    //                            };
    //                            si_CreateMemberShip_obService _si_CreateMemberShip_obService = new si_CreateMemberShip_obService();
    //                            dt_UploadMemberShip_req _dt_UploadMemberShip_req = new dt_UploadMemberShip_req();
    //                            _dt_UploadMemberShip_req.ZCRMT316 = new ZCRMT316[] { _ZCRMT316 };
    //                            dt_UploadMemberShip_res _dt_UploadMemberShip_res = _si_CreateMemberShip_obService.si_CreateMemberShip_ob(_dt_UploadMemberShip_req);
    //                            if (_dt_UploadMemberShip_res.WV_RETURN == "Y")
    //                            {
    //                                //Label1.Text = "注册成功";
    //                                AlertMessage("注册成功");

    //                            }

    //                            //Response.Redirect("Index.aspx");
    //                        }
    //                        catch (Exception ex)
    //                        {
    //                            Label1.Text = "SPA注册失败:" + ex.Message.ToString();
    //                        }
    //                    }

    //                }
    //            }
    //        }
    //    }
    //}
    #endregion

    private string ResMessage(string username, string telephone, string sex, string fendian, string source)
    {      
        MicroService.MicroServiceSoapClient c = new MicroService.MicroServiceSoapClient();
        MicroService.ServicesSoapHeader soapHead2 = new MicroService.ServicesSoapHeader();
        soapHead2.UserName = "baicaoji_crm";
        soapHead2.PassWord = "2014#$crm_bcj";
        string message = c.CreateAppointmentMember(soapHead2, "", username, telephone, sex, fendian, source);
        return message;        
    }

    private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string token = Token();
        Label1.Text = "";
        if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
        {
            string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
            string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
            Session["FromUserName"] = user;
            Session["ToUserName"] = user2;
            if (Session["RanNum"] == null)
            {
                AlertMessage("请先获取验证码");
                return;
            }
            if (txtPhone.Value == "")
            {
                Label1.Text = "请输入手机号码";
            }
            else
            {
                si_DispMember_obService s1 = new si_DispMember_obService();
                dt_DispMember_req w1 = new dt_DispMember_req();
                w1.ZTYPE = "0101";
                w1.MOB_NUMBER = txtPhone.Value.Trim();
                dt_DispMember_res dt1 = s1.si_DispMember_ob(w1);
                if (dt1.ZCRMT316 != null)
                {
                    Label1.Text = "客户已存在，请进行绑定";
                }
                else
                {
                    PersonInfo per = pbo.GetModel(user);
                    if (per != null)
                    {
                        Label1.Text = "你已注册成功";
                    }
                    else 
                    {
                        if (xm.Value == "")
                        {
                            Label1.Text = "请输入真实姓名";
                        }
                        else if (qy.SelectedValue == "0")
                        {
                            Label1.Text = "请选择区域";
                        }
                        else if (ddlYear.SelectedValue == "0")
                        {
                            Label1.Text = "请选择出生年份";
                        }

                        else if (txtPhone.Value == "")
                        {
                            Label1.Text = "请输入手机号码";
                        }
                        else if (txtEmail.Value == "")
                        {
                            Label1.Text = "请输入邮箱";
                        }
                        else if (dx.Value == "")
                        {
                            Label1.Text = "请输入验证码";
                        }
                        else if (Session["RanNum"] != null && Session["RanNum"].ToString() != dx.Value)
                        {
                            Label1.Text = "验证码错误";
                        }
                        else
                        {
                            string message = ResMessage(xm.Value.Trim(), txtPhone.Value.Trim(), ddlSex.SelectedValue, "8889", "001");
                            string[] b = message.Split('|');
                            ////CRM系统存在该会员
                            //if (b[1] == "N" && b[0].Contains("会员已存在请做会员修改"))
                            //{
                            //    Label1.Text = "客户已存在，请进行绑定";
                            //}
                            //创建新注册会员
                            if (b[1] == "Y")
                            {
                                DateTime st = DateTime.Now;
                                try
                                {

                                    st = DateTime.Parse(ddlYear.SelectedValue + "-" + ddlYue.SelectedValue + "-" + ddlDay.SelectedValue);
                                }
                                catch (Exception)
                                {
                                    Label1.Text = "生日格式错误";
                                    return;
                                }
                                PersonInfo p = new PersonInfo();
                                p.area = qy.SelectedValue;
                                p.addr = "";
                                p.BIRTHDAY = st;
                                p.CreateDate = DateTime.Now;
                                p.EMAIL = "";
                                p.FromUserName = user;
                                p.LAST_DATE = DateTime.Now;
                                p.MEM_DATE = DateTime.Now;
                                p.MEM_LEVEL = "注册会员";
                                p.Name = xm.Value;
                                p.PersonNo = txtPhone.Value;
                                p.Phone = txtPhone.Value;
                                p.REMARK = "";
                                if (ddlSex.SelectedValue == "1")
                                {
                                    p.Sex = false;
                                }
                                else if (ddlSex.SelectedValue == "2")
                                {
                                    p.Sex = true;
                                }
                                p.Store = "";
                                p.SumIntegral = 0;
                                p.SurplusIntegral = 0;
                                p.WX_DATE = DateTime.Now;
                                p.YZM = dx.Value;

                                ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
                                string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + user;
                                string bc = PostRequest(url);
                                string[] a = bc.Split('\"');
                                if (a.Length == 35)
                                {
                                    if (a[9].ToString() != "")
                                    {
                                        p.WXName = a[9].ToString();                                     
                                    }
                                }
                                int id = pbo.Add(p);                             
                                if (id > 0)
                                {
                                    si_UploadMemberShip_obService s = new si_UploadMemberShip_obService();
                                    dt_UploadMemberShip_req w = new dt_UploadMemberShip_req();
                                    ZCRMT316 z = new ZCRMT316();
                                    z.TYPE = "0101";
                                    z.BPEXT = p.PersonNo;
                                    z.MOB_NUMBER = p.Phone;
                                    z.ZC023 = user;
                                    w.ZCRMT316 = new ZCRMT316[] { z };
                                    dt_UploadMemberShip_res dt = s.si_UploadMemberShip_ob(w);
                                    if (dt.WV_RETURN == "Y")
                                    {
                                        AlertMessage("注册成功");
                                        string Access_token = Token();
                                        var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
                                        string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""恭喜你注册成功,获赠一张携程电子抵用券（100元）,使用密码为：dfcf100""
    }
}";
                                        d = d.Replace("{0}", Session["FromUserName"].ToString());
                                        var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);

                                    }

                                }

                            }

                        }

                    }

                }
            }
        }
    }

    public void AlertMessage(string message)
    {
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='Index.aspx';</script>");
    }


    //protected void Button3_Click(object sender, EventArgs e)
    //{
    //    int id = int.Parse(numT.Value);
    //    id--;
    //    numT.Value = id.ToString();
    //    divT.InnerHtml = "(" + id.ToString() + "秒后可以重新获取)";
    //    if (id == 0)
    //        divT.InnerHtml = "获取短信验证码";
    //}
}